package org.example.util;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class MyHandlerException implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter printWriter=httpServletResponse.getWriter();
        String mess="";
        if(e instanceof FlowException){
            mess="流控异常";
        }
        if(e instanceof ParamFlowException){
            mess="热点异常";
        }
        if(e instanceof AuthorityException){
            mess="授权异常";
        }
        if (e instanceof SystemBlockException){
            mess="系统异常";
        }
        if (e instanceof DegradeException){
            mess="熔断异常";
        }
        int status=httpServletResponse.getStatus();
        printWriter.print("{\"code\":\""+ status + "\",\"message\":\""+mess + "\"}");
        printWriter.flush();
        printWriter.close();
    }
}
